package com.example.c5;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * @author Jonathan
 * 2021/5/30 0:13
 */
public class EventLoopClient {
//    static final Logger log = Logger.getLogger(EventLoopClient.class);

    public static void main(String[] args) throws InterruptedException {
//        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture channelFuture = new Bootstrap().group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
        // 上面获取到的是一个异步的future
        /*channelFuture.sync();  // 上面是异步的  这个地方阻塞住当前线程
        channelFuture.channel();
        System.out.println("hello world");*/


        // 回调函数
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                Channel channel = channelFuture.channel();
                System.out.println("channel:" + channel);
                channel.writeAndFlush("hello,world.");
            }
        });

    }
}
